package com.michael.retail.commons.pojo.global;


import java.io.Serializable;

/**
 * 类功能描述:
 * <pre>
 *   JSON 返回值封装
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/7/3 17:31
 */
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 结果码
     */
    private Integer code;

    /**
     * 结果消息,一般为错误提示消息
     */
    private String msg;

    /**
     * 响应数据
     */
    private T data;

    private long timestamp;

    public R(){ }

    private R(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.timestamp = System.currentTimeMillis();
    }

    /**
     * 成功 - 无响应数据,默认消息
     */
    public static <T> R<T> succeed() {
        return succeedWith(null, 0, "操作成功");
    }

    /**
     * 成功 - 无响应数据,有消息
     */
    public static <T> R<T> succeed(String msg) {
        return succeedWith(null, 0, msg);
    }

    /**
     * 成功 - 有响应数据,默认消息
     */
    public static <T> R<T> succeed(T data) {
        return succeedWith(data, 0, "操作成功");
    }

    /**
     * 成功 - 有响应数据,有消息
     */
    public static <T> R<T> succeed(T data, String msg) {
        return succeedWith(data, 0, msg);
    }

    /**
     * 失败 - 无响应数据,有消息
     */
    public static <T> R<T> failed(String msg) {
        return failedWith(null, 1, msg);
    }

    /**
     * 失败 - 有响应数据,有消息
     */
    public static <T> R<T> failed(T data, String msg) {
        return failedWith(data, 1, msg);
    }

    private static <T> R<T> succeedWith(T data, Integer code, String msg) {
        return new R<>(code, msg, data);
    }

    private static <T> R<T> failedWith(T data, Integer code, String msg) {
        return new R<>(code, msg, data);
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }
}
